<!--生成提货卡页面-->
<template>
  <div class="form-submit">
    <div class="i-layout-page-header">
      <PageHeader class="product_tabs" hidden-breadcrumb>
        <div slot="title">
          <router-link
              :to="{ path: '/admin/user/recharcard/list' }"
          >
            <div class="font-sm after-line">
              <span class="iconfont iconfanhui"></span>
              <span class="pl10">返回</span>
            </div>
          </router-link>
          <span
              v-text="$route.params.id ? '编辑提货卡' : '添加提货卡'"
              class="mr20 ml16"
          ></span>
        </div>
      </PageHeader>
    </div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Form :model="formData" :label-width="180">
        <FormItem label="提货卡类型：" props="recharcard_type" required>
          <div
              class="productType"
              :class="formData.recharcard_type == item.id ? 'on' : ''"
              v-for="(item, index) in recharcardType"
              :key="index"
              @click="recharcardTypeTap(item)"
          >
            <div
                class="name"
                :class="formData.recharcard_type == item.id ? 'on' : ''"
            >
              {{ item.name }}
            </div>
            <div class="title">({{ item.title }})</div>
            <div v-if="formData.recharcard_type == item.id" class="jiao"></div>
            <div
                v-if="formData.recharcard_type == item.id"
                class="iconfont iconduihao"
            ></div>
          </div>
        </FormItem>
        <div style="width: 80%;color: red;margin: 10px auto;font-size: 18px;" v-show="formData.recharcard_type === 2">
          生成商品券请注意：1.单个商品不支持设置兑换数量，选择任一个商品兑换数量都为1；2.不支持同一个商品选择多次！，无法兑换使用</div>
        <FormItem label="选择商品 :" v-show="formData.recharcard_type === 2" required>
          <template>
            <div
                class="upload-list"
                v-for="item in productList"
                :key="item.product_id"
                @change="productChange"
            >
              <img :src="item.image" />
              <Icon
                  type="ios-close-circle"
                  size="16"
                  @click="remove(item.product_id)"
              />
            </div>
          </template>
<!--          <Icon type="ios-camera-outline" size="26" @click="modals = true" style="border: 1px solid red;" />-->
          <Icon type="ios-camera-outline" size="26" @click="productmodals = true"  />
<!--           <div class="info"></div>-->
        </FormItem>

        <FormItem label="选择商品的分类 :" v-show="formData.recharcard_type === 3" required>
          <el-cascader
              :options="categoryList"
              :props="props"
              @change="casChange"
              clearable></el-cascader>
        </FormItem>
        <FormItem label="提货卡名称" required>
          <Input
              v-model="formData.recharcard_title"
              v-width="320"
              placeholder="请输入提货卡名称"
          ></Input>
        </FormItem>
        <FormItem label="提货卡面值" required>
          <InputNumber
              :min="1"
              :max="100000000"
              v-model="formData.recharcard_money"
              v-width="320"
              placeholder="请输入提货卡金额"
          ></InputNumber>
          <span class="ml10">{{"元"  }}</span>
        </FormItem>
        <FormItem label="单位名称" prop="company">
          <Input type="text"  v-model="formData.company" placeholder="请输入提货卡使用公司" ></Input>
          <span class="ml10">给指定公司生成提货卡时填写</span>
        </FormItem>
        <FormItem label="提货卡编号" prop="start_no" required>
          <Input type="text"  v-model="formData.start_no" ></Input>
          <br><span style="color: red;font-weight: bolder;font-size: 18px;margin: 5px 0">编号一定要紧跟上一次生成的编号，否则会造成编号重复【可在生成记录中查询提货卡编号】</span>
          <br><span style="color: red;font-weight: bolder;font-size: 18px;margin: 5px 0">编号示例：050002（格式：金额/5位自增数字【不够5位自动补全】）</span>
        </FormItem>
        <FormItem label="请选择提货卡封面图片：" prop="formData.recharcard_img" required>
          <div class="picBox" @click="modalPicTap('单选')">
            <div class="pictrue" v-if="formData.recharcard_img">
              <img style="max-width: 600px;max-height: 400px;" :src="formData.recharcard_img">
            </div>
            <div class="upLoad acea-row row-center-wrapper" v-else>
              <Icon type="ios-camera-outline" size="26" />
            </div>
          </div>
        </FormItem>
        <FormItem v-show="isMinPrice" required>
          <InputNumber
              :min="1"
              :max="100000000"
              v-model="formData.use_min_price"
          ></InputNumber>
          <div class="info">填写提货卡的最低消费金额</div>
        </FormItem>
        <FormItem label="提货卡数量" required>
          <InputNumber
              :min="1"
              :max="100000000"
              v-model="formData.total_count"
              :precision="0"
          ></InputNumber>
          <span class="ml10">填写提货卡的发布数量</span>
        </FormItem>
        <FormItem label="是否开启">
          <i-switch
              v-model="formData.status"
              :true-value="1"
              :false-value="0"
              size="large"
          >
            <span slot="open">开启</span>
            <span slot="close">关闭</span>
          </i-switch>
        </FormItem>
        <FormItem label="提货卡使用规则：" prop="recharcard_rule_id">
          <Select
              v-model="formData.recharcard_rule_id"
              clearable
              filterable
              v-width="'30%'"
              placeholder="请选择提货卡规则"
          >
            <Option
                v-for="(item, index) in recharRuleArr"
                :value="item.value"
                :key="item.value"
            >{{ item.label }}</Option
            >
          </Select>
<!--          <span class="addClass" @click="addUnit" v-if="merchantType!=1">新增单位</span>-->
        </FormItem>
      </Form>
    </Card>
    <Card
        :bordered="false"
        dis-hover
        class="fixed-card"
        :style="{ left: `${!menuCollapse ? '200px' : isMobile ? '0' : '80px'}` }"
    >
      <Form>
        <FormItem>
          <Button type="primary" @click="save" :disabled="disabled"
          >立即创建</Button
          >
        </FormItem>
      </Form>
    </Card>
    <!-- 商品列表弹窗层    -->
    <Modal
        v-model="productmodals"
        title="商品列表"
        footerHide
        class="paymentFooter"
        scrollable
        width="900"
        @on-cancel="cancel"
    >
      <goods-list
          ref="goodslist"
          v-if="productmodals"
          :ischeckbox="true"
          @getProductId="getProductId"
      ></goods-list>
    </Modal>
    <!-- 提货卡封面图选择模块弹窗  -->
    <Modal v-model="modalPic" width="960px" scrollable footer-hide closable title='上传商品图' :mask-closable="false"
           :z-index="999">
      <uploadPictures :isChoice="isChoice" @getPic="getPic" :gridBtn="gridBtn" :gridPic="gridPic" v-if="modalPic">
      </uploadPictures>
    </Modal>

  </div>
</template>

<script>
import { mapState } from "vuex";
import goodsList from "@/components/goodsList/index";
import uploadPictures from '@/components/uploadPictures';
import {  couponCategoryApi,/*获取商品分类*/ couponSaveApi2,
  couponDetailApi,
} from "@/api/marketing";
import {receiveRuler, RecharcardSaveApi} from "@/api/user" ;
import { formatDate } from '@/utils/validate';
export default {
  name: "recharCardCreate",
  components: {
    goodsList,
    uploadPictures
  },
  data() {
    return {
      props: { multiple: true },
      isChoice: '单选',
      recharcardType: [
        { name: "提货卡余额充值", title: "充值到用户余额", id: 1 },
        { name: "商品提货卡", title: "提货卡兑换指定商品使用", id: 2 },
        { name: "分类专区提货卡", title: "充值兑换指定专区商品使用", id: 3 },
      ],
      disabled: false,
      // recharcard_use_type 使用时间选择哪个 1为天数 2为时间段   recharcard_use_time 这个是天数和时间段字段
      // 提货卡类型 提货卡名称 提货卡图片 分类id  提货卡面值
      time:'',
      time2:'',
      recharRuleArr:[], // 提货卡规则数组
      formData: {
        recharcard_type:1, //提货卡类型
        recharcard_title: '', //提货卡名称
        recharcard_img: '', //提货卡图片
        category_id: '', //分类id
        product_id :[], //商品ID
        recharcard_money : 0 , //提货卡面值
        total_count : 0 , //数量
        // recharcard_use_type:1, //使用时间选择 1为天数 2为时间段
        // recharcard_use_time:0, //天数和时间段字段
        status : 1, //状态
        image :[],    //商品提货卡选择后显示的商品图片 array
        recharcard_rule_id : '' , //规则
        company:'', //单位名称
        start_no:'',//卡编号开始字段
      },
      categoryList: [],
      productList: [],
      isMinPrice: 0,
      isCouponTime: 1,
      isReceiveTime: 0,
      productmodals: false,
      datetime1: [],
      datetime2: [],
      modalPic:false,
      gridPic: {
        xl: 6,
        lg: 8,
        md: 12,
        sm: 12,
        xs: 12
      },
      gridBtn: {
        xl: 4,
        lg: 8,
        md: 8,
        sm: 8,
        xs: 8
      },
    };
  },
  computed: {
    ...mapState("admin/layout", ["isMobile", "menuCollapse"]),
  },
  created() {
    this.getCategoryList();   //获取商品分类
    this.recharRule();     //获取提货卡规则
    if (this.$route.params.id) {
      console.log('created  456')
      this.getCouponDetail();
    }
  },
  methods: {

    // 提货卡封面图片上传方法
    modalPicTap() {
      this.modalPic = true
    },
    getPic(pc) {
      this.formData.recharcard_img = pc.att_dir;
      this.modalPic = false;
    },
    //选择提货卡类型
    recharcardTypeTap(item) {
      this.formData.recharcard_type = item.id;
    },
    // 品类
    getCategoryList() {
      couponCategoryApi(1).then(async (res) => {
        res.data.forEach((val) => {
          val.cate_name = `${val.html}${val.cate_name}`;
        });
        this.categoryList = res.data;
      });
    },
    //提货卡规则
    recharRule(){
      receiveRuler().then(async (res) => {
        this.recharRuleArr = res.data;
      })
    },
    // 提货卡
    getCouponDetail() {
      couponDetailApi(this.$route.params.id)
          .then((res) => {
            console.log(res,'couponDetailApi11111111111')
            let data = res.data;
            this.formData.recharcard_title = data.recharcard_title;
            this.formData.recharcard_type = data.recharcard_type;
            this.formData.type = data.type;
            this.formData.category_id = data.category_id;
            this.formData.recharcard_title = parseFloat(data.recharcard_title);
            this.formData.use_min_price = parseFloat(data.use_min_price);
            this.formData.coupon_time = data.coupon_time;
            // this.formData.receive_type = data.receive_type;
            this.formData.is_permanent = data.is_permanent;
            this.formData.status = data.status;
            this.formData.product_id = data.product_id;
            this.formData.start_time = data.start_time;
            this.formData.end_time = data.end_time;
            this.formData.total_count = data.total_count;
            this.formData.sort = data.sort;
            if ("productInfo" in data) {
              console.log(data,'data22222222');
              this.productList = data.productInfo;
            }
            if (!data.coupon_time) {
              this.isCouponTime = 0;
              this.datetime1 = [
                data.start_use_time * 1000,
                data.end_use_time * 1000,
              ];
              this.formData.start_use_time = this.makeDate(
                  data.start_use_time * 1000
              );
              this.formData.end_use_time = this.makeDate(
                  data.end_use_time * 1000
              );
            }
            if (data.start_time) {
              this.isReceiveTime = 1;
              this.datetime2 = [data.start_time * 1000, data.end_time * 1000];
              this.formData.start_time = this.makeDate(data.start_time * 1000);
              this.formData.end_time = this.makeDate(data.end_time * 1000);
            }
            if (data.use_min_price !== "0.00") {
              this.isMinPrice = 1;
            }
          })
          .catch((err) => {
            this.$Message.error(err.msg);
          });
    },
    makeDate(data) {
      let date = new Date(data);
      let YY = date.getFullYear() + "-";
      let MM =
          (date.getMonth() + 1 < 10
              ? "0" + (date.getMonth() + 1)
              : date.getMonth() + 1) + "-";
      let DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      let hh =
          (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      let mm =
          (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
          ":";
      let ss =
          date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return YY + MM + DD + " " + hh + mm + ss;
    },
    //分类选择 douhao逗号分割多个分类
    casChange(e){
      e.forEach(item=>{
        if(this.formData.category_id == ''){
          this.formData.category_id = item[1]
        }else{
          this.formData.category_id += ',' + item[1]
        }
      })
    },
    //商品选择 douhao逗号分割多个商品
    productChange(e){
      e.forEach(item=>{
        if(this.formData.product_id == ''){
          this.formData.product_id = item[1]
        }else{
          this.formData.product_id += ',' + item[1]
        }
      })
    },
    // 提货卡创建方法
    save() {
      if (this.formData.recharcard_type === 2) {
        if (this.formData.product_id == '') {
          return this.$Message.error("请选择提货卡使用商品");
        }
      }

      if (this.formData.recharcard_type === 3) {
        if (this.formData.category_id == '') {
          return this.$Message.error("请选择提货卡使用商品分类");
        }
      }
      if (this.formData.recharcard_title == '') {
        return this.$Message.error("请输入提货卡名称");
      }
      if (this.formData.recharcard_money <= 0) {
        return this.$Message.error("提货卡面值不能小于0");
      }
      if (this.formData.start_no == '') {
        return this.$Message.error("提货卡编号不能为空");
      }
      if(this.formData.recharcard_img == ''){
        return this.$Message.error("请上传提货卡封面图片");
      }
      if (this.formData.total_count < 1) {
        return this.$Message.error("提货卡数量不能能小于1");
      }
       if (this.formData.recharcard_rule_id < 1) {
        return this.$Message.error("请选择该提货卡使用规则");
      }
      console.log('this.formData',this.formData)
      this.disabled = true;
      RecharcardSaveApi(this.formData)
          .then((res) => {
            this.$Message.success(res.msg);
            setTimeout(() => {
              this.disabled = false;
              this.$router.push({
                path: "/admin/user/recharcard/list",
              });
            }, 3000);
          })
          .catch((err) => {
            this.disabled = false;
            this.$Message.error(err.msg);
          });
    },
    change(){
      this.time = ''
      this.formData.recharcard_use_time = 0
    },
    // 商品提货卡 选择多个商品处理商品ID方法
    getProductId(productList) {
      this.productmodals = false; // 关闭商品选择弹窗层
      this.productList = Array.from(new Set(this.productList.concat(productList))); // 使用 ES6 Set 去重，然后转为数组
      this.formData.image = '';
      const mid_product_id = this.productList.map(({ product_id }) => product_id).join(','); // 提取 product_id 属性，然后使用 join 方法将数组转为字符串
      this.formData.product_id = mid_product_id;
      // if (!this.formData.image) { // 通过图片判断是商品提货卡还是分类提货卡
      //   console.log(`${this.productList.length}个商品提货卡`);
      // }
    },
    cancel() {
      this.modals = false;
    },
    // 删除商品
    remove(productId) {
      for (let index = 0; index < this.productList.length; index++) {
        if (this.productList[index].product_id == productId) {
          this.productList.splice(index, 1);
        }
      }
      this.formData.product_id = "";
      this.productList.forEach((value) => {
        if (this.formData.product_id) {
          this.formData.product_id += `,${value.product_id}`;
        } else {
          this.formData.product_id += `${value.product_id}`;
        }
      });
    },
  },
};
</script>

<style scoped lang="stylus">
.picBox {
  display: inline-block;
  cursor: pointer;
}
.form .pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 10px;
}

.form .pictrue img {
  width: 100%;
  height: 100%;
}
.productType {
  width: 200px;
  height: 60px;
  background: #FFFFFF;
  border-radius: 3px;
  border: 1px solid #E7E7E7;
  float: left;
  text-align: center;
  padding-top: 8px;
  position: relative;
  cursor: pointer;
  line-height: 23px;
  margin-right: 12px;

&.on {
   border-color: #1890FF;
 }

.name {
  font-size: 14px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.85);

&.on {
   color: #1890FF;
 }
}

.title {
  font-size: 12px;
  font-weight: 400;
  color: #999999;
}

.jiao {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 0;
  height: 0;
  border-bottom: 26px solid #1890FF;
  border-left: 26px solid transparent;
}

.iconfont {
  position: absolute;
  bottom: -3px;
  right: 1px;
  color: #FFFFFF;
  font-size: 12px;
}
}

.info {
  color: #888;
  font-size: 12px;
}

.ivu-input-wrapper {
  width: 320px;
}

.ivu-input-number {
  width: 160px;
}

.ivu-date-picker {
  width: 320px;
}

.ivu-icon-ios-camera-outline {
  width: 58px;
  height: 58px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  background-color: rgba(0, 0, 0, 0.02);
  line-height: 58px;
  cursor: pointer;
  vertical-align: middle;
}

.upload-list {
  width: 58px;
  height: 58px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  margin-right: 15px;
  display: inline-block;
  position: relative;
  cursor: pointer;
  vertical-align: middle;
}

.upload-list img {
  display: block;
  width: 100%;
  height: 100%;
}

.ivu-icon-ios-close-circle {
  position: absolute;
  top: 0;
  right: 0;
  transform: translate(50%, -50%);
}

.form-submit {
/deep/.ivu-card {
  border-radius: 0;
}

margin-bottom: 79px;

.fixed-card {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 200px;
  z-index: 99;
  box-shadow: 0 -1px 2px rgb(240, 240, 240);

/deep/ .ivu-card-body {
  padding: 15px 16px 14px;
}

.ivu-form-item {
  margin-bottom: 0;
}

/deep/ .ivu-form-item-content {
  margin-right: 124px;
  text-align: center;
}

.ivu-btn {
  height: 36px;
  padding: 0 20px;
}
}
}
</style>
